package com.shopping.security;

import java.io.IOException;
import java.util.List;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;
    // 构造函数注入 JwtUtil
    @Autowired
    public JwtAuthenticationFilter(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        log.info("调用过滤器");
        final String authorizationHeader = request.getHeader("Authorization");
        log.info(authorizationHeader);
        String username = null;
        String jwt = null;

        // 解析 JWT
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            username = jwtUtil.extractUsername(jwt); // 从 JWT 中提取用户名
        }

        // 如果用户未认证，设置 Spring Security 上下文
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 提取用户角色
            String role = jwtUtil.extractUserRole(jwt);
            log.info("用户名：{}，用户角色：{}", username, role);//校验日志

            // 创建一个 Authentication 对象
            UserDetails userDetails = new org.springframework.security.core.userdetails.User(username, "", List.of(new SimpleGrantedAuthority(role)));
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken); // 设置认证信息
        }

        filterChain.doFilter(request, response); // 继续处理请求
    }
}